#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#include "ardew.h"
#include "led.h"

uint16_t lastrawinput = 0;
uint16_t currentinput = 0;
uint8_t  ackinput     = 0;

int main() {
  ardew_setup();
  confpins(2, 12, 1);

  checkinput();
  ackinput = 0;
  while (1) {
    checkinput();
    if (currentinput & (1 << LEFTBUTTON)) {
      if (currentinput & (1 << RIGHTBUTTON)) { // haz
        hazardsignal();
      } else {
        leftsignal();
      }
    } else if (currentinput & (1 << RIGHTBUTTON)) {
      rightsignal();
    } else {
      idlesignal();
    }
    ackinput = 0;
  }
}

uint16_t checkinput() {
  /*
  if (has_input_waiting(serialport)) {
    currentinput = read_serial(serialport);
    return 1;
  }
  */
  uint16_t newinput = getinputbits(14, 19); // 14 = A0, 19 = A5
  if (newinput != currentinput) {
    currentinput = newinput;
    ackinput = 1;
    return 1;
  }
  return 0;
}

void checksleepms(uint16_t ms) {
  uint16_t i;
  i = ms;
  while (i > 0) {
    checkinput();
    if (ackinput) return;
    if (SLEEPSLICEMS >= i) {
      _delay_ms(i);
      return;
    } else {
      _delay_ms(SLEEPSLICEMS);
      i -= SLEEPSLICEMS;
    }
  }
}

void checksetwait(uint16_t outputbits, uint8_t lowpin, uint8_t highpin, uint16_t delayms) {
  if (ackinput) return;
  setoutputbits(outputbits, lowpin, highpin);
  checksleepms(delayms);
}

void hazardsignal() {
  checksetwait(0x7df, 2, 12, 500);
  checksetwait(0x000, 2, 12, 500);
}

void leftsignal() {
  checksetwait(0x01f, 2, 12, 500);
  checksetwait(0x000, 2, 12, 500);
}

void rightsignal() {
  checksetwait(0x7c0, 2, 12, 500);
  checksetwait(0x000, 2, 12, 500);
}

void idlesignal() {
  checksetwait(0x000, 2, 12, 20);
}
